import { getRepository } from 'typeorm';
import { User } from '../entity/User';
async function auth(req, res, next) {
  // console.log('req', req.path);
  if (req.url.indexOf('/api') === -1) {
    await next();
    return;
  }
  // 我做了个假的token验证（好像没什么必要整），没用reids,token不会变,前端浏览器关闭就删除。
  // 白名单：有些操作我们是不需要鉴权的
  const whitelist = ['/api/users/login', '/api/users/register', '/api/upload'];
  if (!whitelist.includes(req.path)) {
    // console.log('非白名单请求');
    // console.log('headers', req.headers.token);
    if (req.headers.token) {
      let username = req.headers.token.split('*')[0];
      let token = req.headers.token.split('*')[1];

      let userRepository = getRepository(User);
      let user = await userRepository.findOne({ username: username });

      if (user.token === token) {
        await next();
        return;
      } else {
        res.send({
          message: '访问令牌鉴权无效，请重新登陆获取！',
          code: 401,
          success: false,
        });
        return;
      }
    } else {
      res.send({
        message: '访问令牌鉴权无效，请重新登陆获取！',
        code: 401,
        success: false,
      });
      return;
    }
  }
  await next();
}
module.exports = { auth };
